<template>
  <div class="content">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';

const data = ref([
  {
    userCount: 1000,
    articleCount: 500,
    publishedArticleCount: 450,
    draftArticleCount: 50,
    commentCount: 2000,
    pendingCommentCount: 30,
    viewCount: 100000,
    likeCount: 5000,
    categoryCount: 20,
    tagCount: 100
  }
]);

const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: ECharts | null = null;

const initChart = () => {
  if (!chartRef.value) return;
  if (chartInstance) {
    chartInstance.dispose();
  }

  const { width, height } = chartRef.value.getBoundingClientRect();
  chartInstance = echarts.init(chartRef.value, null, { width, height });

  const chartData = [
    { name: '用户数', value: data.value[0].userCount },
    { name: '文章数', value: data.value[0].articleCount },
    { name: '评论数', value: data.value[0].commentCount },
    { name: '点赞数', value: data.value[0].likeCount },
    { name: '浏览量', value: data.value[0].viewCount }
  ];

  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: chartData.map(item => item.name)
    },
    series: [
      {
        name: '平台数据',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData
      }
    ]
  };

  // 设置图表选项
  chartInstance.setOption(option);
};

// 监听窗口大小变化，重绘图表
const handleResize = () => {
  if (chartInstance && chartRef.value) {
    const { width, height } = chartRef.value.getBoundingClientRect();
    chartInstance.resize({ width, height });
  }
};

// 组件挂载时初始化图表
onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

// 监听数据变化，更新图表
watch(data, () => {
  initChart();
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});
</script>

<style scoped>
.content {
  background-color: white;
  width: 90%;
  height: 393px;
  margin-left: 5%;
  padding: 20px;
}

.chart-container {
  width: 100%;
  height: 100%;
}
</style>
